// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: AGPL-3.0-or-later

package config

import (
	"os"

	"github.com/BurntSushi/toml"
	"notabug.org/apiote/gott"
)

// TODO change to dirty

type Auth struct {
	ApiKey    string
	KeyHeader string
}

type Config struct {
	FeedsPath     string
	EnabledFeeds  []string
	ListenAddress string
	Auth          map[string]Auth
}

type result struct {
	configPath string
	configFile *os.File
	config     Config
}

func openFile(input ...interface{}) (interface{}, error) {
	args := input[0].(result)
	configFile, err := os.Open(args.configPath)
	args.configFile = configFile
	return gott.Tuple{args}, err
}

func scan(input ...interface{}) (interface{}, error) {
	args := input[0].(result)
	configFile := args.configFile
	config := args.config
	decoder := toml.NewDecoder(configFile)
	_, err := decoder.Decode(&config)

	args.config = config

	configFile.Close()

	return gott.Tuple{args}, err
}

func Read(configPath string) (Config, error) {
	input := gott.Tuple{
		result{
			configPath: configPath,
			config: Config{
				EnabledFeeds:  []string{},
				FeedsPath:     "/var/lib/szczanieckiej",
				ListenAddress: ":51354",
				Auth:          map[string]Auth{},
			},
		},
	}
	output, err := gott.NewResult(input).
		Bind(openFile).
		Bind(scan).
		Finish()
	if err != nil {
		return Config{}, err
	}
	return output.(gott.Tuple)[0].(result).config, nil
}
